Uec3.ReceiveEditWindow = Ext.extend(Ext.app.Module, {
   id: 'receive_edit',
   type: 'common/receive',//?
   readOnlyStyle:{background:'#dddddd', width:'120px'},   
   uecId:null,
   getPanel:function(params){
   	        var _this =this;
			var deleteItemsId=[];
	        var datas=[];//存放新增记录的集合
			var toatalCount;
			//创建数据
     var receive_item_record = Ext.data.Record.create([
		    {name:'id'},
		    {name:'partId'},
		    {name:'code'},
		    {name:'name'},
		    {name:'source'},
		    {name:'carModel'},
		    {name:'measurementUnit'},
		    {name:'orderQuantity'},
		    {name:'quantity'},
		    {name:'cost'},
		    {name:'costAmount'},
		    {name:'retailPrice'},
		    {name:'minPrice'},
		    {name:'insurancePrice'},
		    {name:'publicanLevel'},
		    {name:'brand'},
		    {name:'origin'},
		    {name:'storeId'},
		    {name:'storePyCode'},
		    {name:'storeName'},
		    {name:'shelf'},
		    {name:'receiveId'},
		    {name:'inventoryIdBySeller'},
			{name:'ordersItemId'},
		    {name:'nameEn'},
		    {name:'pyCode'},
		    {name:'partCategoryId'},
		    {name:'level1Name'},
		    {name:'level2Name'},
		    {name:'level1Id'},
		    {name:'durability'}		    
		]
		);
	  
		//定义数据传递形式	  
	 var receive_item_store = new Ext.data.JsonStore({	
	 	    //remoteSort:false,
	        root: "",
	        idProperty: "id",
	        pruneModifiedRecords:true,
	        fields:receive_item_record
	     });
	     
	  var ds_source_select = new Ext.data.JsonStore({
	      url:Uec3.App.Constants.homeUrl+"/dictionary/findByVarGroup.do?group=part_source",
	      root: "",
	      //autoLoad :true,
	      fields:[{name:'varIndex',type:'int'},{name:'varName',type:'string'}]
	  });   
	   
	  var ds_publicanLevel_select = new Ext.data.JsonStore({
	      url:Uec3.App.Constants.homeUrl+"/dictionary/findByVarGroup.do?group=partproperty_publicanLevel",
	      root: "",
	      //autoLoad :true,
	      fields:[{name:'varIndex',type:'int'},{name:'varName',type:'string'}]
	  });
	  
	   var ds_measurementUnit_select = new Ext.data.JsonStore({
	      url:Uec3.App.Constants.homeUrl+"/part/unit_getUnits.do",
	      //root: "root",
	      //autoLoad :true,
	      fields:[{name:'name'}]
	  });
	  
	  var ds_availableOrder_select=new Ext.data.JsonStore({
	  	  //url:Uec3.App.Constants.homeUrl+"/purchase/availabeOrder!getAvailabeOrders.do",
	      root:'',	      
	      fields:['id','codeOfBuyer']
	  });
	  
	  var ds_code_select = new Ext.data.JsonStore({
	     url:Uec3.App.Constants.homeUrl+"/part/queryPart!getPartByCodeImplicitExt.do",
	     root:'root',
	     totalProperty:'totalProperty',
         fields:[{name:'code',type:'string'},{name:'name',type:'string'}]
	  });
		  
	  var store_ds = new Ext.data.JsonStore({
		url : Uec3.App.Constants.homeUrl+ '/store/base!query.do',
		root:'root',
		totalProperty: "totalProperty",
		fields:[
			{name : 'id',type:'int'},
			{name : 'name',type:'string'},
			{name : 'pyCode',type:'string'},
			{name : 'departmentName',type:'string'}
		]
	});
	  
  var source_comboBox= new Ext.form.ComboBox({
       typeAhead: true,
	   width : 120,
	   valueField:'varIndex',
	   displayField : 'varName',
   	   mode : 'local',
	   hiddenName:'source',
	   store : ds_source_select,
	   selectOnFocus : true,
	   triggerAction : 'all',
	   allowBlank : false,
	   loadingText : '加载中...',
	   editable:false,
	   emptyText : '请选择'
  });
  
  var publicanLevel_comboBox= new Ext.form.ComboBox({
       typeAhead: true,
	   width : 120,
	   valueField:'varIndex',
	   displayField : 'varName',
   	   mode : 'remote',
   	   hiddenName:'publicanLevel',
	   store : ds_publicanLevel_select,
	   selectOnFocus : true,
	   forceSelection  :true,
	   triggerAction : 'all',
	   allowBlank : false,
	   loadingText : '加载中...',
	   editable:false,
	   emptyText : '请选择',
	   valueNotFoundText:''
  });
  
   var resultTpl = new Ext.XTemplate(
            '<tpl for="."><div class="search-item">',
               '{name},{departmentName}',             
            '</div></tpl>'
   );
  
   var storeId_comboBox= new Ext.form.ComboBox({
       typeAhead: true,
	   hiddenValue:'id',
	   displayField : 'name',
	   //hiddenId: 'storeName_'+new Date().getTime(),	 
   	   mode : 'remote',
	   store : store_ds,
	   tpl: resultTpl,
   	   itemSelector: 'div.search-item',
	   selectOnFocus : true,
	   forceSelection  :true,
	   triggerAction : 'all',
	   valueNotFoundText:'',
	   loadingText : '加载中...',
	   editable:false,
	   pageSize:5,
	   listWidth :220,
	   emptyText : '请选择'
  }); 
	 
  var ds_partner_store = new Ext.data.JsonStore({
	   url: Uec3.App.Constants.homeUrl+"/partner/query_partner!queryPartner.do",
	   root:'root',   
       totalProperty: 'totalProperty',  	      
	   baseParams:{start:0,limit:4,type:1},
	   fields: [{name:'id'},{name:'pyCode'},{name:'name'},{name:'companyId'}]
  });
  
	var partner_combox = getPartnerLookup(1,{grid:[2,3,2,3],allowBlank : false});
  
	partner_combox.on({
		'select':function(lookupBox,record,index){
		   	   selectPartnerCombo(lookupBox, record, index);			 
			},
			'lookupChange': function(record, creator, oldValue, win){
				 lookupChangePartnerCombo(record, creator, oldValue, win);
			},
			'lookupClear' : function(){
				resetWholeRecieve("确定删除该供货商?");	               			              		
			},
		    scope:this
	});
	
	 
	function  selectPartnerCombo(lookup, record, index){
		if(lookup.getValue() && (lookup.getValue() + '').trim() != '' && lookup.getValue() != record.data.id ) {
			Ext.MessageBox.confirm("提示", '确定更改供货单位?',function(btnId){
				if(btnId == "no"){
					return;
				}else{
					if(orderId_combox.getValue() && (orderId_combox.getValue()+'').trim() != ''){
						resetPartner();						
					}
					lookup.setValue(record.data[lookup.valueField], record.data[lookup.lookupField]);
					setParamForField(record);
				}
			});
		}else if(!lookup.getValue()){
			lookup.setValue(record.data[lookup.valueField], record.data[lookup.lookupField]);
			setParamForField(record);
		}
	}
	
	function lookupChangePartnerCombo(record, creator, oldValue, win){
		if(oldValue && (oldValue + '').trim() != '' && record.data.id != oldValue ){
			Ext.MessageBox.confirm("提示", '确定更改供货单位?',function(btnId){
				if(btnId == "no"){
					return;
				}else{
					if(orderId_combox.getValue() && (orderId_combox.getValue()+'').trim() != ''){
						resetPartner();						
					}
					creator.setLookupValue(record.data, win);
					setParamForField(record);
				}
			});
		}else if(!oldValue){
			creator.setLookupValue(record.data, win);
			setParamForField(record);
		}
	}
	
	function setParamForField(record){
		receive_form.getForm().findField("sellerId").setValue(record.data.companyId);
		var partnerId = record.data.id;
	}
	
	var orderId_combox = getOrderIdLookup('codeOfBuyer',{ grid:[4,3,4,3],triggerTags : [{moduleId: 'purchaseQueryWindowCreator',triggerClass:'x-form-search-trigger',params:{partnerCmb : partner_combox}}]});
	
	orderId_combox.on({
		'lookupChange':function(record){
			var id= record.data.id;
				if(Ext.isEmpty(id)){
					Ext.MessageBox.alert("提示","请确定是否正确引用销售订单!");
				}else{
					initByOrderId(id);	  	           	  	 
				}	                              
		},
		'lookupClear' : function(){
			receive_item_store.removeAll();
			toolbar.enable();
		}
	});
	  	       
	  
	   var colName= new Ext.grid.ColumnModel({	   	
	      columns:[	
	      	new Ext.grid.RowNumberer(),
	       {header:'零件编码',dataIndex:'code',css:'background-color:#dddddd;',width:110},
	       {header:'零件名称',dataIndex:'name',css:'background-color:#dddddd;',width:110},
	       {header:'来源',dataIndex:'source',css:'background-color:#dddddd;',width:90,renderer:Ext.util.Format.comboRenderer(source_comboBox)},
	       {header:'品牌',dataIndex:'brand',width:80,css:'background-color:#dddddd;'},
	       {header:'车型',dataIndex:'carModel',css:'background-color:#dddddd;'},
	       {header:'产地',dataIndex:'origin',width:80,editor : new Ext.form.TextField()},
	       //{header:'单位',dataIndex:'measurementUnit',css:'background-color:#dddddd;',width:60},
	       {header:'订购数量',dataIndex:'orderQuantity',css:'background-color:#dddddd;',width:80},
	       {header:'数量',dataIndex:'quantity',width:80,editor : new Ext.form.NumberField({ allowBlank: false,allowNegative: false})},
	       {header:'进价',dataIndex:'cost',width:80,css:'background-color:#dddddd;',editor : new Ext.form.NumberField({ allowBlank: false,allowNegative: false})},
	       {header:'媒体价',dataIndex:'retailPrice',width:80},
	        /*{header:'最低价',dataIndex:'minPrice',width:80},
	       {header:'保险价',dataIndex:'insurancePrice',width:80},
	       {header:'公开级别',dataIndex:'publicanLevel',width:110},	*/       
	       
		   {header:'仓库',dataIndex:'storeName',width:120,editor:storeId_comboBox},
           {header:'仓位',dataIndex:'shelf',width:80,editor : new Ext.form.TextField()}
	   ],
	    defaults: {
          //sortable: true,
          menuDisabled: true
          //width:120
       }
    });
	   
	   	//创建工具栏组件
		var toolbar = new Ext.Toolbar({
		  items:[
			{text : '新增明细',iconCls : 'icon-add',itemId:'addItemButton',handler:showAddDetail},
			{text : '编辑明细',iconCls : 'icon-edit',itemId:'editItemButton',handler:showModifyDetail},
			{text : '删除明细',iconCls : 'icon-del',itemId:'deleteItemButton',handler:showDeleteDetail}
		   ]
		});
	   //创建grid，装载明细数据

	   var receive_item_grid=new Ext.grid.EditorGridPanel({	
	   	   region : 'center',
	   	   //height:270,	   	   
	   	   viewConfig:
	   	   	{	   	   	  
	   	      scrollOffset:20
	   	     },	   	   
	   	   autoScroll : true,
	   	   titleCollapse:true,
	   	   clicksToEdit:1,
	       colModel:colName,
	       //enableColumnResize:false,
	       selModel:new Ext.grid.RowSelectionModel(
	                     {moveEditorOnEnter:true,
	                      singleSelect :true
	                     }
	       ),
	       store:receive_item_store,	           
	       columnLines :true,	       
	       tbar:toolbar,
	       loadMask:{mag:'单据加载中,请稍后....'},
	       listeners : {
	         'afteredit': function checkThePrice(e){
	   	    				 if(e.field=='quantity'){
	   	      					 var orderQuantity = e.record.data.orderQuantity;
	   	       					 if(e.value > orderQuantity){
	   	       					      checkPriceOfGrid("实际数量大于订购数量?",e.row, e.column);	   	         						 	                                
	   	      					 }
	   	    				 }
	   	    				 var cost = e.record.data.cost;
	   	    				 var retailPrice = e.record.data.retailPrice;
	   	    				 var minPrice = e.record.data.minPrice;
	   	    				 var insurancePrice = e.record.data.insurancePrice;
	   	    				 if(e.field == 'retailPrice'){
	   	    				        if(e.value < cost){
	   	    				      	    checkPriceOfGrid("确定媒体价小于进价?",e.row, e.column);	   	    				         
	   	    				        }	   	    				      
	   	    				 }
	   	    				 if(e.field == 'minPrice'){
	   	    				 		if(e.value < cost){
	   	    				 			checkPriceOfGrid("确定最低价小于进价?",e.row, e.column);	   	    				            
	   	    				        }
	   	    				        if(e.value > retailPrice){
	   	    				        	checkPriceOfGrid("确定最低价大于媒体价?",e.row, e.column);		   	    				             	   	    				        
	   	    				        }
	   	    				 }
	   	    				 if(e.field == 'insurancePrice'){
	   	    				        if(e.value < cost){
	   	    				        	checkPriceOfGrid("确定保险价小于进价?",e.row, e.column);	   	    				            
	   	    				        }
	   	    				        if(e.value > retailPrice){
	   	    				        	checkPriceOfGrid("确定保险价大于媒体价?",e.row, e.column);	   	    				               	    				        
	   	    				        }
	   	    				 }
	   	    				 if(e.field=='storeName'){
	   	    				 	 //alert("change storeId");
	   	    				     var storeName = storeId_comboBox.getRawValue();
	   	    				     var store = storeId_comboBox.getStore();
	   	    				     var index = store.find(storeId_comboBox.displayField,storeName);
	   	    				     var storeId = store.getAt(index).get("id");
	   	    				    
	   	    				     e.record.set('storeId',storeId); 
	   	    				 }
	   					}
	       }	      
	   });
	   	  	
	   /**
	    * grid中明细验证：采购数量，媒体价，最低价，保险价
	    */
	   function checkPriceOfGrid(msg,rowIndex,colIndex){
	        Ext.MessageBox.confirm("提示",msg,function(btnId){
	   	    	  if(btnId == 'no'){
	   	         	 //receive_item_grid.getView().focusCell(e.row, e.column); 
	   	    		  receive_item_grid.getView().getCell(rowIndex, colIndex).style.backgroundColor="#D2B48C";
	   	          }
	   	    }); 
	   }	   	 
	        
	  //得到records总记录数
	  function getTotalRecords(){
	      var totalRecords=receive_item_store.getCount();	     
	      return totalRecords;
	  }
	  
	  //取得选中的记录
	  function getSelectedItem(){
	     var record= receive_item_grid.getSelectionModel().getSelected();	   
	     if(record == null){
	         Ext.MessageBox.alert('提示','请选择要进行操作的入库明细！');
	         return;
	     }else{
	        return record;
	     }
	  }
	  
	  //显示增加明细弹出窗口
	   function showAddDetail(){	     		
	   	    _this.app.desktop.launchWindowByParam("addReceiveItem",{grid:receive_item_grid,isAdd:true});
	   }
	  
	   //显示修改明细弹出窗口
	   function showModifyDetail(){	  	
	   	    var record=getSelectedItem();
	   	    if(Ext.isEmpty(record)){
	   	      return;
	   	    }else{
	   	      var orderId = orderId_combox.getValue();
	   	      var hasOrder;
	   	      if(Ext.isEmpty(orderId)){
	   	      	 hasOrder = false;
	   	      }else{
	   	      	hasOrder = true;
	   	      }
	   	      _this.app.desktop.launchWindowByParam("addReceiveItem",{grid:receive_item_grid,isAdd:false,record:record});
	   	    }
	  }
	  //显示删除明细弹出窗口  
	  function showDeleteDetail(){
	     var record = getSelectedItem();
	     var receive_item_id =record.data.id;
	     Ext.Msg.confirm("提示","确定删除所选记录",function(btnId){    
	         if(btnId=="yes"){
	         	if(receive_item_id){
	     	      //将删除的记录的id放入数组中	     	    
	              deleteItemsId.push(receive_item_id);
	             }	                      
	            receive_item_grid.getStore().remove(record);
	            receive_item_grid.getView().refresh();
	         }
	     });
	     
	  }
	   
	 
	   var operation=function(btn){
			eval(btn.func+"(btn)");
	   }
	 
	  function fillHeaderAndGrid(receiveObj){
	      if(typeof receiveObj == 'string'){
		     var receiveObj=Ext.util.JSON.decode(receiveObj);
		  }		 
		  var receive_item_main_data=receiveObj.main;
	      var receive_item_detail_data=receiveObj.details;
	      var receive_item_buttons = receiveObj.buttons.buttons;
	      var isOwner = receiveObj.buttons.isOwner;
	      var msg = receiveObj.msg;	      
	      //填充入库单表头(主表)
	      receive_form.getForm().setValues(receive_item_main_data);
	     /* Ext.getDom("partnerName").value = receive_item_main_data.partnerName;
	      Ext.getDom("partnerIdByBuyer").value = receive_item_main_data.partnerIdByBuyer;*/
	      partner_combox.initializeValue({'name':receive_item_main_data.partnerNameByBuyer,'pyCode':receive_item_main_data.partnerPyCodeByBuyer,'id':receive_item_main_data.partnerIdByBuyer});
	      orderId_combox.initializeValue({'codeOfBuyer':receive_item_main_data.codeOfOrder,'id':receive_item_main_data.ordersId});
	      //填充入库单明细表(从表)
	      receive_item_store.loadData(receive_item_detail_data);
	      //状态条
	      receive_status_panel.getForm().setValues(receive_item_main_data);
	       //判断是否所有者打开当前单据,页面不同展示效果
	      rendererSpecificColumnByConditon(isOwner);	           
    	  //显示相应按钮条
	      fillButtons(receive_item_buttons,operation,receive_status_panel);
	      if(msg.confirm){
	      	  toPayInvoice(msg.confirm,receiveObj.payableId,receiveObj.customerId);	        
	      }else if(msg.alert){
		  	  Ext.MessageBox.alert("提示",msg.alert);
	      }	      
	  }
	  
	  	function toPayInvoice(msg,payableId,customerId){
	  		Ext.MessageBox.confirm("提示",msg,function(btnId){
		       if(btnId == 'yes'){
		  	      //跳转付款单页面		  	  	  
		         _this.app.desktop.launchWindowByParam("payInvoice_operation",{winId:'receive'+payableId,payableIds:payableId,customerId:customerId});
		       }
            });
	  	}
	  
	  var fieldList=['partnerIdByBuyer','ordersId','codeOfSeller','gmtAccept','memo'];
	  function disableSpecificField(){ 
	     Ext.each(fieldList,function(item,index,array){
	         var field = receive_form.getForm().findField(item);
	         field.setReadOnly(true);	        
	         field.getEl().setStyle('background','#dddddd');
	     });    
	  }
	  
	  function enableSpecificField(){
	  	 Ext.each(fieldList,function(item,index,array){
	         var field = receive_form.getForm().findField(item);
	         field.setReadOnly(false);
	         field.getEl().setStyle('background','');
	     }); 
	  }
	  /**
	   * 根据单据状态页面不同编辑效果
	   */
	  function rendererSpecificColumnByConditon(isOwner){
	  	  var status =  receive_form.getForm().findField("status").getValue();
	  	  var quantityColumn = getColumnByDataIndex("quantity");
	  	  var costColumn = getColumnByDataIndex("cost");
	  	  var originColumn = getColumnByDataIndex("origin");
	  	  var storeIdColumn = getColumnByDataIndex("storeName");
	  	  var shelfColumn = getColumnByDataIndex("shelf");
	  	  var receive_item_gridView = receive_item_grid.getView().mainBody;
	  	  var gridMask =new Ext.LoadMaskJUPIT(receive_item_gridView);					
	      if(status == 1){
	      	  disableSpecificField();
	      	  if(!isOwner){	      	  
	             gridMask.show();
	             toolbar.disable();
	      	  }else{
	      	  	 gridMask.hide();
	      	     toolbar.getComponent("addItemButton").disable();
	      	     toolbar.getComponent("deleteItemButton").disable();
	      	     toolbar.getComponent("editItemButton").enable();	      	    
			     disableSpecificColumn([quantityColumn,costColumn,originColumn])
	      	  }	     	   
	      }else if( status == 2){
	      	  disableSpecificField();
	      	  gridMask.show();
	      	  toolbar.disable();
	      }else{
	      	  if(!isOwner){
	      	     disableSpecificField();
	      	     toolbar.disable();
	      	     gridMask.show();
	      	  }else{
	      	  	 enableSpecificField();	      	  	
	      	  	 gridMask.hide();
	      	  	 if(orderId_combox.getValue()){
	      	  	 	toolbar.getComponent("addItemButton").disable();
	      	     	toolbar.getComponent("deleteItemButton").disable();
	      	     	disableSpecificColumn([costColumn,originColumn]);
	      	  	 }
	      	  	 toolbar.enable();	      	  	
	      	  }	     	  
	     }	   
	  }
	  
	 
	  function disableSpecificColumn(arr){
	      Ext.each(arr,function(item,index,arr){
	      	item.css = 'background-color: #dddddd;';
	      	delete item.editor;
	      });
	  }
	  
	  function getColumnByDataIndex(dataIndex){
	  		var columnModel = receive_item_grid.getColumnModel();
	        var columnIndex = columnModel.findColumnIndex(dataIndex);
	      	var columnId = columnModel.getColumnId(columnIndex);
	      	var column = columnModel.getColumnById(columnId);
	  		return column;
	  }
	  
	  function getColumnIndexByDataIndex(dataIndex){
	  		var columnModel = receive_item_grid.getColumnModel();
	        var columnIndex = columnModel.findColumnIndex(dataIndex);
	        return columnIndex;
	  }
	  
	    function getColumnByIndex(index){
	    	var columnModel = receive_item_grid.getColumnModel();
	        var columnId = columnModel.getColumnId(index);
	      	var column = columnModel.getColumnById(columnId);
	  		return column;
	  }
	  
	  function readyToHandleOrder(id){
	  	if(id=='yes'){
	  	   var ordersId = orderId_combox.getValue();
	  	   var myMask = new Ext.LoadMask(join_panel.ownerCt.el,{msg : "正在接手采购订单,请稍后....."});
           myMask.show();
	       Ext.Ajax.request({
	           url:Uec3.App.Constants.homeUrl+"/receive/toReceive!acceptOrderToReceive.do",
	           params :{queryParam:ordersId},
	           method :"post",
	           callback :function(options,success,response){
	               myMask.hide();      
	           },
	           success:function(response,options){
					 var resp = Ext.decode(response.responseText);
					 if(resp.success){
					     var data = resp.order;					    				   
	                     var data_detail = resp.orderItem;	                       
	     				 partner_combox.initializeValue({'name':data.partnerNameByBuyer,'pyCode':data.partnerPyCodeByBuyer,'id':data.partnerIdByBuyer});
	      				 orderId_combox.initializeValue({'codeOfBuyer':data.codeOfBuyer,'id':data.ordersId});
	      				 delete data.codeOfBuyer;
	      				 //填充入库单表头(主表)
	      				 receive_form.getForm().setValues(data); 
	      				 //填充入库单明细表(从表)
	      				 receive_item_store.loadData(data_detail);
	      				 initButtons();
					 }else{
						 Ext.MessageBox.alert("提示",resp.msg);
					 }
	           },
	           failure:function(response,options){
	                Ext.MessageBox.alert("提示","发生异常，请稍候处理!");    
	           }
	       });
	     }
	  }
	     /*
	    * 页面整体布局
	    */
	   //状态面板
	   var receive_status_panel = new Ext.form.FormPanel({	   	   
			labelAlign:'left',
			region :'south',
			height:65,
			frame:true,
			items:[
				{
					layout:'uec3grid',
					layoutConfig:{
						hGrid:[6,7,5,7,6,7,5,7,6,7,5,7,6,7,5,7],
						vGrid:[100]					  	
					},
					height:26,
					defaultType:'textfield',
					items:[
						{
							xtype:'label',
							text:'订单状态:',
						 	//style : {font : 'bold 18px arial, serif',textAlign : 'center'},
						 	grid : [1, 1, 1, 1]
						},{
							name:'statusName',
							disabled:true,
							grid : [2,1,2,1]
						},{
							xtype:'label',
							text:'创建人:',
						 	//style : {font : 'bold 18px arial, serif',textAlign : 'center'},
						 	grid : [3, 1, 3, 1]
						},{
							name:'creatorName',
							disabled:true,
							grid : [4,1,4,1]
						},{
							xtype:'label',
							text:'创建时间:',
						 	//style : {font : 'bold 18px arial, serif',textAlign : 'center'},
						 	grid : [5, 1, 5, 1]
						},{
							name:'gmtCreate',
							disabled:true,
							grid : [6,1,6,1]
						},{
							xtype:'label',
							text:'提交人:',
						 	//style : {font : 'bold 18px arial, serif',textAlign : 'center'},
						 	grid : [7, 1, 7, 1]
						},{
							name:'submitterName',
							disabled:true,
							grid : [8,1,8,1]
						},{
							xtype:'label',
							text:'提交时间:',
						 	//style : {font : 'bold 18px arial, serif',textAlign : 'center'},
						 	grid : [9, 1, 9, 1]
						},{
							name:'gmtSubmit',
							disabled:true,
							grid : [10,1,10,1]
						},{
							xtype:'label',
							text:'审核人:',
						 	//style : {font : 'bold 18px arial, serif',textAlign : 'center'},
						 	grid : [11, 1, 11, 1]
						},{
							name:'depositerName',
							disabled:true,
							grid : [12,1,12,1]
						},{
							xtype:'label',
							text:'审核时间:',
						 	//style : {font : 'bold 18px arial, serif',textAlign : 'center'},
						 	grid : [13, 1, 13, 1]
						},{
							name:'gmtDepositer',
							disabled:true,
							grid : [14,1,14,1]
						},{
							xtype:'label',
							text:'总金额:',
						 	//style : {font : 'bold 18px arial, serif',textAlign : 'center'},
						 	grid : [15, 1, 15, 1]
						},{
							name:'amount',
							disabled:true,
							grid : [16,1,16,1]
						}
					]				
				}
			]		
	   });
	   
	    //主表面板         
        var receive_form = new Ext.FormPanel({            
			frame : true,
			region : 'north',
			width:'100%',
			layout:'uec3grid',
			layoutConfig:{
				hGrid:[6,28,7,18,7,13,6,15],
				vGrid:[25,15,30,30]					  	
			},
			height:110,
			items:[
				{
					xtype:'label',
					text:'采购入库单',
				 	style : {font : 'bold 18px arial, serif',textAlign : 'center'},
				 	grid : [3, 1, 5, 1]
				},{
					xtype : 'label',
					text : '单据号:',
					style:{fontSize:'13px',marginLeft:'9px'},
					grid : [7,1,7,1]
				},{
					xtype:'textfield',
					name : 'codeOfBuyer',							 
				    readOnly :true,
				    style : _this.readOnlyStyle,
				    grid:[8,1,8,1]
				},{
					html:'<hr color="#34A4E0" />',
					grid:[1,2,8,2]
				},{
				    xtype:'label',
				    text:'供货单位:',
				    grid:[1,3,1,3]				   
				},partner_combox,
				{
                   xtype:'label',
                   text:'引用订单号:',
                   grid:[3,3,3,3],
                   style:{marginLeft:'2px'}
                },orderId_combox,
                {
				   xtype:'label',
				   text:'卖方单据号:',
				   grid:[5,3,5,3],
				   style:{marginLeft:'2px'}
				},{
				   xtype : 'textfield',							 
				   name : 'codeOfSeller',
				   grid:[6,3,6,3]
				},{
				   xtype:'label',
				   text:'收货时间:',
				   grid:[7,3,7,3],
				   style:{marginLeft:'2px'}
				},{
				   xtype : 'datefield',
				   name : 'gmtAccept',
				   width:150,
				   allowBlank:false,
				   format:'Y-m-d H:i:s',
				   grid:[8,3,8,3]
				},{
				   xtype:'label',
				   text:'备注:',
				   grid:[1,4,1,4]
				},{
				   xtype : 'textarea',
				   name : 'memo',
				   grid:[2,4,8,4],
				   autoScroll:true
				},{
          	       xtype:'hidden',
				   name:'id'
          	    },{
				   xtype:'hidden',
  	    		   name:'sellerId'	
				},{
		           xtype : 'hidden',					        
		           name:'status'
		       }
			]            	           
       });
   
				function getAllReceiveItems(checkStore){
					    if(!receive_form.getForm().isValid()){
					       return;
					    }
					    var item =receive_form.getForm().getValues();
					    if(Ext.isEmpty(item.partnerIdByBuyer,false)){
						   Ext.MessageBox.alert('提示','请选择供货商!');	
						   return;
						}							
						var store=receive_item_grid.getStore();		
						var totalRecords=store.getRange(0,store.getCount());						
			            var receiveItems=[];
						for(var i=0;i<totalRecords.length;i++){
							var record=totalRecords[i].data;
							if(checkStore){
								if(Ext.isEmpty(record.storeId)){
							  		Ext.MessageBox.alert("提示",'仓库不能为空!');
							 		return;
								}
							}							
							receiveItems.push(record);
						}
						if(Ext.isEmpty(receiveItems)){
			                Ext.MessageBox.alert('提示','未有入库明细!');
			                return;
			            }											
					    var receive={main:item,details:receiveItems,deleteItemIds:deleteItemsId};
						var receiveObj=Ext.util.JSON.encode(receive);							
						return receiveObj;
					}			
		
		function backupReceiveAndItems(btn,msg,wait,checkStore){
		    var receive = getAllReceiveItems(checkStore);		    
		    if(!Ext.isEmpty(receive)){
		    	Ext.MessageBox.confirm("提示",msg,function(btnId){
		    		if(btnId == 'yes'){
		    			var myMask = new Ext.LoadMask(join_panel.ownerCt.el,{msg :wait});
                        myMask.show();
                        Ext.Ajax.request({				
							url:btn.url,
							method :"post",	
							timeout:180000,
							params:{queryParam:receive},
							callback :function(options,success,response){
	                     		 myMask.hide();
	            			},
							success:function(response,options){								
					 			var resp = Ext.decode(response.responseText);
								if(resp.success){					   
					   				 fillHeaderAndGrid(resp);					    			
					    			 changeWindowUecId(resp.main.codeOfBuyer,"receive_edit","receive_edit_"+resp.main.id);
					 			 }else{
					                  Ext.MessageBox.alert("提示",resp.msg);
					             }					            
			   				},
			   				failure:function(response,options){                			
			   					Ext.MessageBox.alert('提示','网络连接异常，请稍候处理!', 'error');	                			
	           				}
						});
		    		  }
		    	 });
		     }				  
		 }
		
		/**
		 * 接受或释放单据
		 */
		function acceptOrReleaseReceive(btn,msg,wait){
		   var receiveId = receive_form.getForm().findField("id").getValue();
		   if(!Ext.isEmpty(receiveId)){
		    	Ext.MessageBox.confirm("提示",msg,function(btnId){
		    		if(btnId == 'yes'){
		    			var myMask = new Ext.LoadMask(join_panel.ownerCt.el,{msg : wait});
                        myMask.show();
                        Ext.Ajax.request({
	           				url:btn.url,
	           				params :{queryParam:receiveId},
	           				method :"post",
	           				timeout:180000,
	           				callback :function(options,success,response){	                     
	           				},
	          				success:function(response,options){
					 			var resp = Ext.decode(response.responseText);
					 			if(resp.success){
					 				var buttons = resp.buttons;
					 				var isOwner = resp.isOwner;					 				
	                  				//显示相应按钮条
	                    			fillButtons(buttons,operation,receive_status_panel); 
	                    			rendererSpecificColumnByConditon(isOwner);
							    }else{
					    			Ext.MessageBox.alert("提示",resp.msg);
								}
								myMask.hide();
	          				 },
	           				 failure:function(response,options){
	                				Ext.MessageBox.alert("提示","网络连接异常，请稍候处理!");  
	                				myMask.hide();
	           				  }
	       				});
		    		  }
		    	 });
		     }					   
	     }
	     //根据id删除入库单
	     function deleteDraft(btn){
	          var receiveId = receive_form.getForm().findField("id").getValue();
	          if(!Ext.isEmpty(receiveId)){
		    	 Ext.MessageBox.confirm("提示","确定删除入库单草稿?",function(btnId){
		    		if(btnId == 'yes'){
		    			var myMask = new Ext.LoadMask(join_panel.ownerCt.el,{msg : "入库单草稿删除中,请稍后...."});
                        myMask.show();
	         		    Ext.Ajax.request({
	             			url:btn.url,
	             			params :{queryParam:receiveId},
	             			method :"post",
	             			callback :function(options,success,response){},
	             			success:function(response,options){
	             				var resp = Ext.decode(response.responseText);
	             				if(resp.success){	             	   				
	             					receive_form.ownerCt.close();
	             					redirectUrl("receive_browser");
	                			}
	             				Ext.MessageBox.alert("提示",resp.msg);
	             				myMask.hide();
	             			},
	             			failure:function(response,options){
	               				 Ext.MessageBox.alert("提示","网络连接异常，请稍候处理!"); 
	               				 myMask.hide();
	             			}
	          			});
		    		 }				
		    	});
	          }
	     }
	     /**
	      * 待入库单据退回草稿
	      */
	     function backToDraft(btn){
	        var receiveId = receive_form.getForm().findField("id").getValue();
	        if(!Ext.isEmpty(receiveId)){
		    	 Ext.MessageBox.confirm("提示","确认待入库单退回草稿?",function(btnId){
		    		if(btnId == 'yes'){
		    			var myMask = new Ext.LoadMask(join_panel.ownerCt.el,{msg : "退回草稿中,请稍后...."});
                        myMask.show();
	         		    Ext.Ajax.request({
	             			url:btn.url,
	             			params :{queryParam:receiveId},
	             			method :"post",
	             			timeout:180000,
	             			callback :function(options,success,response){},
	             			success:function(response,options){
					 			var resp =Ext.decode(response.responseText);
					 			if(resp.success){					 	
					    			fillHeaderAndGrid(resp);					     
					 			}else{
					     			Ext.MessageBox.alert("提示",resp.msg)
					 			}
					 			myMask.hide();
	             			},
	             			failure:function(response,options){
	                			Ext.MessageBox.alert("提示","网络连接异常，请稍候处理!"); 
	                			myMask.hide();
	             			}
	          			});
		    		 }				
		    	});
	         }
	     }
	     /**
	      * 保存草稿
	      */
	     function backupDraft(btn){	     	
	     	backupReceiveAndItems(btn,"确定保存草稿?","草稿保存中,请稍后.....");
	     }
	     /**
	      * 保存待仓库点数入库单
	      */
	     function submit(btn){
	     	backupReceiveAndItems(btn,"确定保存单据为待入库状态?","待入库单据保存中,请稍后.....");
	     }
	     /**
	      * 确认入库
	      */
	     function deposit(btn){
	     	backupReceiveAndItems(btn,"确定入库?","入库单正在保存中,请稍后.....",true);
	     }
	     /**
	      * 接受单据
	      */
	     function acceptReceive(btn){
	     	acceptOrReleaseReceive(btn,"确定接手单据?","正在接手单据,请稍后.....");
	     }
	     /**
	      * 释放单据
	      */
	     function releaseReceive(btn){
	     	acceptOrReleaseReceive(btn,"确定释放单据?","正在释放单据,请稍后.....");
	     }
	     /**
	      * 打印入库单
	      */
	     function printReceive(btn){
		if (!Ext.fly('test')){ 
			var frm = document.createElement('form'); 
			frm.id = 'test'; 
			frm.style.display = 'none'; 
			document.body.appendChild(frm); 
		} 
		Ext.Ajax.request({ 
			url:Uec3.App.Constants.homeUrl+"/receive/printReceive.do",
			form: Ext.fly('test'), 
			method: 'POST',   
		    isUpload: true,
		    success:function(response){
		    	
		    }
		}); 
	}
	    /**
	     * 跳转入库单浏览页面
	     */
	     function receiveBrowser(btn){
	    	 redirectUrl("receive_browser");
	     }
	     /**
	      * 跳转新增采购订单页面
	      */
	     function newCreateReceive(btn){	       
	    	 redirectUrl("receive_edit");
	     }
	     /**
	      * 新建表单重置
	      */
	     function reset(btn){
	     	  resetWholeRecieve("确定清空表单?");	
	     }
	     
	     function resetWholeRecieve(msg){
	     	Ext.MessageBox.confirm("提示",msg,function(btnId){
		    	if(btnId == 'yes'){
		    		var myMask = new Ext.LoadMask(join_panel.ownerCt.el,{msg : "处理中,请稍后...."});
                       myMask.show();
	         		   partner_combox.clearValue();
	     			   resetPartner();
	    	 		   myMask.hide();
		    	}				
		    });	   	     	
	     }
	     
	     function resetPartner(){
	     	orderId_combox.clearValue();
	     	receive_form.getForm().reset();
	     	receive_status_panel.getForm().reset();
	    	receive_item_store.removeAll();
	     }
	     /**
	      * 退出
	      */
	     function exit(btn){	
	     	Ext.MessageBox.confirm("提示","确定退出?",function(btnId){
		    		if(btnId == 'yes'){
		    			join_panel.ownerCt.close();
		    		 }				
		     });				
		 }
	     
	     function redirectUrl(id,params){
	     	var desktop =Uec3.App.getDesktop();   
	 		desktop.launchWindowByParam(id,params); 	 		
	     }
     	
         init();
		 function init(){		    	
		 	ds_source_select.load();
		    ds_publicanLevel_select.load();		    
		    ds_measurementUnit_select.load();		   	  
		   /* if(params&&params.id){
		    	initByReceiveId(params.id);
		    }else{
		       initButtons();
		    }*/
		   
		 } 
		 
		 Ext.util.Observable.capture(receive_form,function(e){
		    if(e == 'render'){
		        if(params&&params.id){
		    	   initByReceiveId(params.id);
		        }else if(params&&params.orderId){
		        	orderId_combox.initializeValue({'codeOfBuyer':params.codeOfBuyer,'id':params.orderId});
		        	initByOrderId(params.orderId);
		        }else{
		            initButtons();
		        }
		    }
		 });
		 
		 
	/**
	 * 初始化按钮
	 */						
	function initButtons(){
			var myMask = new Ext.LoadMask(join_panel.ownerCt.el,{msg : "按钮加载中,请稍后...."});
		    myMask.show();
			Ext.Ajax.request({
			       url:Uec3.App.Constants.homeUrl+"/receive/toReceive!getInitialButtons.do",			       
    		       callback :function(options,success,response){	                     
	               		myMask.hide();
	               },
    		       success: function(response,options){
    			       var resp =Ext.decode(response.responseText);
    			       var buttons = resp.buttons;					 	
	                  	//显示相应按钮条
	                   fillButtons(buttons,operation,receive_status_panel);
    		       },
    		       failure: function(response,options){
    			       Ext.MessageBox.alert("提示","初始化按钮出错!");
    		       },
    		       scope: this
			 });
	 }
	
	function initByReceiveId(id){	
		var myMask = new Ext.LoadMask(join_panel.ownerCt.el,{msg : "单据加载中,请稍后...."});
		myMask.show();
		Ext.Ajax.request({
		       url:Uec3.App.Constants.homeUrl+"/receive/toReceive!getReceiveAndItemById.do",
		       params: {queryParam:id},
		       callback :function(options,success,response){
                 myMask.hide();
               },
		       success: function(response,options){
			       var resp =Ext.decode(response.responseText);
			       if(resp.success){
			    	   fillHeaderAndGrid(resp);
			    	   //改变窗口的title	    	  
			    	   changeWindowUecId(resp.main.codeOfBuyer,params.uecId);
			       }else{
			    	   Ext.MessageBox.alert("提示",resp.msg);
			       }
		       },
		       failure: function(response,options){
			       Ext.MessageBox.alert("提示","加载数据错误!");
		       },
		       scope: this
		 });
	}
	
	function initByOrderId(id){
		var myMask = new Ext.LoadMask(join_panel.ownerCt.el,{msg : "正在处理中,请稍后....."});
     	myMask.show();
     	Ext.Ajax.request({
    		url :Uec3.App.Constants.homeUrl+"/receive/orderForReceive.do",
    		params :{queryParam:id},
    		method :"post",
    		callback :function(options,success,response){
                 myMask.hide();
    		},
    		success:function(response,options){
    			var receive = Ext.decode(response.responseText);
    			if(receive.success){
    				if(receive.hasReceive){
    					receive_form.form.reset();					     
						fillHeaderAndGrid(receive);
    				}else{
    				     Ext.MessageBox.confirm("提示",receive.msg.confirmFirst,readyToHandleOrder);
    				}
    				toolbar.getComponent("addItemButton").disable();
	      	     	toolbar.getComponent("deleteItemButton").disable();
    			}else{
    				Ext.MessageBox.alert("提示",receive.msg);
    			}					        
    		},
    		failure:function(response,options){
         		 Ext.MessageBox.alert("提示","数据加载异常");
    		}
		});
	}
	
	var join_panel = new Ext.Container({
		layout:'border',
		items:[receive_form,receive_item_grid,receive_status_panel]
	});
	
	return join_panel;   
},
   /**
    * Initialize this module.
    * This function is called at startup (page load/refresh).
    */
   init : function(initParams){
   		
   },
	/**
	 * Create this modules window here.
	 */
   createWindow : function(params){	 
   	   var _this = this;
 	  var windowId='receive_edit';
  	  if(params&&params.winId){
  	  	windowId+=Ext.isEmpty(params.winId)?"":"_"+params.winId;
  	  }
  	  params.uecId=windowId;
      var desktop = this.app.getDesktop();
      //var win = desktop.getWindow(windowId);
      var win = desktop.getWindowByUecId(windowId);
      if(!win){      	
         win = desktop.createWindow({
            //id: windowId,
         	uecId:windowId,
            title: '入库单',
            width: 1000,
            height: 500,
            minWidth:1000,
            minHeight:500,
            //autoScroll : true,
            iconCls: 'acc-icon',
            shim: false,  
            constrain:true,
            resizable : true,
			resizeHandles :'se',
            animCollapse: false,
            constrainHeader: true,
            maximizable: true,
            taskbuttonTooltip: "采购入库",
            layout: "fit",         
            items:[this.getPanel(params)]         
         });
      }        
      win.show();    
     /* win.on('show',function(){
      	  var myMask = new Ext.LoadMask(win.el,{msg : "加载中,请稍后...."});
		  myMask.show();
		  win.removeAll();
          win.add(_this.getPanel(params));
          win.doLayout();
          myMask.hide();
      },this,{single:true});
      */
      /*win.on('resize',function(win, width, height){
      	win.doLayout();
      });*/
   }
 });
   